var Promise = require('../vendor/es6/es6-promise')

function formatTime(date) {
    var now = new Date();
    var result;
    var millisecond = now.getTime() - date.getTime();
    var secode = millisecond / 1000;
    var minute = secode / 60;
    var hour = minute / 60;
    if (secode <= 60) {
        // 一分钟之前
        result = "刚刚";
    } else if (secode > 60 && minute <= 60) {
        //一小时以内
        result = Math.ceil(minute) + "分钟之前";
    } else if (minute > 60 && hour <= 24) {
        result = Math.ceil(hour) + "小时之前";
    } else {
        console.log("millisecond:" + millisecond);

        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();

        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();

        result = [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
    }

    return result;
}

function formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
}

function formatDistance(distance) {
    var distance = parseFloat(distance);
    if (distance < 100) {
        return '附近';
    } else if (distance < 500) {
        return '<500m';
    } else if (distance < 1000) {
        return '<1km';
    } else {
        return (distance / 1000).toFixed(2) + "km";
    }
}


function wxPromisify(fn) {
    return function (obj = {}) {
        return new Promise((resolve, reject) => {
            obj.success = function (res) {
                resolve(res)
            }

            obj.fail = function (res) {
                reject(res)
            }

            fn(obj)
        })
    }
}

/** 
 * 函数说明：获取字符串长度 
 * 备注：字符串实际长度，中文2，英文1 
 * @param:需要获得长度的字符串 
 */
function getStrLength(str) {
    var realLength = 0, len = str.length, charCode = -1;
    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) {
            realLength += 1;
        } else {
            realLength += 2;
        }
    }
    return realLength;
};

/**  
 * js截取字符串，中英文都能用  
 * @param str：需要截取的字符串  
 * @param len: 需要截取的长度  
 */
function cutStr(str, len) {
    var str_length = 0;
    var str_len = 0;
    var str_cut = new String();
    str_len = str.length;
    for (var i = 0; i < str_len; i++) {
        let a = str.charAt(i);
        str_length++;
        if (escape(a).length > 4) {
            //中文字符的长度经编码之后大于4    
            str_length++;
        }
        str_cut = str_cut.concat(a);
        if (str_length >= len) {
            str_cut = str_cut.concat("...");
            return str_cut;
        }
    }
    //如果给定字符串小于指定长度，则返回源字符串；    
    if (str_length < len) {
        return str;
    }
}


module.exports = {
    formatTime: formatTime,
    wxPromisify: wxPromisify,
    Promise: Promise,
    cutStr: cutStr,
    formatDistance: formatDistance
}


